/*
 * InfosetRepresentation.java
 *
 * Created on April 3, 2007, 10:43 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.app;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import org.infoset.xml.Document;
import org.infoset.xml.XMLException;
import org.infoset.xml.util.XMLWriter;
import org.restlet.data.MediaType;
import org.restlet.representation.OutputRepresentation;

/**
 *
 * @author alex
 */
public class InfosetRepresentation extends OutputRepresentation
{
   
   Document doc;
   /** Creates a new instance of InfosetRepresentation */
   public InfosetRepresentation(MediaType type,Document doc)
   {
      super(type);
      this.doc = doc;
   }
   
   public Document getDocument() {
      return doc;
   }
   
   public String getText() 
      throws IOException
   {
      try {
         StringWriter w = new StringWriter();
         XMLWriter.writeDocument(doc,w);
         return w.toString();
      } catch (XMLException ex) {
         throw new IOException("Cannot serialize XML entity: "+ex.getMessage());
      }
   }
   
   public InputStream getStream() 
      throws IOException
   {
      return new ByteArrayInputStream(getText().getBytes());
   }
   
   public void write(OutputStream os)
      throws IOException
   {
      try {
         Writer w = new OutputStreamWriter(os,"UTF-8");
         XMLWriter.writeDocument(doc,w);
      } catch (XMLException ex) {
         throw new IOException("Cannot serialize XML entity: "+ex.getMessage());
      }
      
   }
   
   
}
